<template>
  <div class="page-user-login">
    <van-nav-bar title="登录"></van-nav-bar>
    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <!-- name属性是表单提交的key属性 -->
      <van-field
        v-model="form.mobile"
        name="mobile"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern, message: '请输入正确内容' },
        ]"
      />
      <van-field
        v-model="form.code"
        name="code"
        label="验证码"
        placeholder="验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { validator, message: '请输入正确内容' },
        ]"
      >
        <template #button>
          <van-button size="small" native-type="button" type="primary"
            >发送验证码</van-button
          >
        </template>
      </van-field>

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'user-chat',
  data () {
    return {
      form: {
        mobile: '18434300871',
        code: '246810'
      },
      pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
    }
  },
  methods: {
    ...mapActions(['getToken']),
    // values是表单内容
    async onSubmit (values) {
      // console.log('submit', values)
      try {
        await this.getToken(values)
        this.$toast.success('登陆成功')
        // 跳转到用户页或者是上次访问的页面
        this.$router.push(this.$route.query.redirectUrl || '/')
      } catch (error) {
        // console.dir(error)
        this.$toast.fail(error.response.data.message)
      }
    },
    validator (val) {
      if (val.length !== 6) return false
      return true
      // return /^\d{6}$/.test(val)
    }
  }
}
</script>

<style scoped lang='less'></style>
